package com.chazz.dao.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.chazz.dao.GoodsDao;

import com.chazz.entity.Goods;
import com.chazz.tools.ConnectionPools;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GoodsDaoImple implements GoodsDao {
    private static ConnectionPools connectionPools = ConnectionPools.getInstace();
    private static DataSource dataSource = connectionPools.getDataSource();
    private static Connection connection = null;

    static {
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据前端传回的分类编号进行商品模糊查询
     *
     * @param categoryId
     */
    @Override
    public List<Goods> GoodsBlurryQuery(int categoryId) {

        List<Entity> entityList = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        try {
            entityList = SqlExecutor.query(connection, "SELECT * FROM goods where categoryid=? ", new EntityListHandler(), categoryId);
            for (Entity entity : entityList) {
                Goods goods = new Goods();
                goods.setGoodsid((Integer) entity.get("goodsid"));
                goods.setGoodsno((String) entity.get("goodsno"));
                goods.setGoodsname((String) entity.get("goodsname"));
                goods.setGoodstitle((String) entity.get("goodstitle"));
                goods.setGoodsimg((String) entity.get("goodsimg"));
                goods.setCategoryid((Integer) entity.get("categoryid"));
                goods.setBrandid((Integer) entity.get("brandid"));
                goods.setGoodsdescription((String) entity.get("goodsdescription"));
                goods.setStatus((Integer) entity.get("status"));
                goods.setCreatetime((Date) entity.get("createtime"));
                goods.setUpdatetime((Date) entity.get("updatetime"));
                goods.setRemark((String) entity.get("remark"));
                goodsList.add(goods);


            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goodsList;
    }

    /**
     * 根据商品id查询具体商品
     *
     * @param goodID
     * @return Goods
     * @author Woo
     */
    @Override
    public Goods findGoods(int goodID) {
        Goods goods = null;
        try {
            goods = (Goods) Db.use().findAll(Entity.create("goods").set("goodsid", "goodID"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goods;
    }

}
